package com.computer.network.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.computer.network.po.SysUser;
import com.computer.network.service.RedisService;
import com.computer.network.service.SysUserService;
import com.computer.network.util.JwtUtil;
import com.computer.network.util.ResultCode;
import com.computer.network.util.ResultToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录成功处理器
 *
 * @Author cgs
 * @Date 2022/8/19 11:33
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private ResultCode resultCode;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisService redisService;
    @Resource
    private SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        //设置编码格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        //获取输入流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //获取当前登录用户信息
        SysUser principal = (SysUser) authentication.getPrincipal();
        //生成token,(方法内部设置过期时间和签名密钥)
        String token = jwtUtil.generateToken(principal);
        ResultToken resultToken = new ResultToken(principal.getId(), resultCode.success, token);
        System.out.println(resultToken);
        //将token信息保存到redis
        redisService.LoginAddRedis(token, principal);

        //登录成功，设置当前用户权限
        // 获取当前用户所具有的角色集合
//        List<Long> longList = sysUserService.selectRoleNameByUserId(principal.getId());
//        //更新用户信息
//        ((SysUser) authentication.getPrincipal()).setRoleId(longList);
        //将用户信息转换成自定义Result格式
//        Result result2 = result1.ok(resultCode.success, principal);
        //将用户信息转换成json格式
        String result = JSON.toJSONString(resultToken, SerializerFeature.DisableCircularReferenceDetect);
        //输出流
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        //清空缓存区
        outputStream.flush();
        //关闭缓存
        outputStream.close();
    }
}
